package com.qunar.wan.email;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

/**
 * User: tongjie.yang Date: 13-11-29 Time: 下午3:14
 */
public class MailMessageFactory {
    private Logger logger = LoggerFactory.getLogger(getClass());
    private MimeMessageHelper mimeMessageHelper;
    private JavaMailSender senderImpl;
    private MimeMessage mimeMessage;
    private SendMessage sendMessage;
    private static final String ENCODING = EmailEntity.EMAIL_ENCODING;

    public MailMessageFactory() {
        this.senderImpl = JavaMailFactory.getJavaMail();
        this.mimeMessage = senderImpl.createMimeMessage();
        sendMessage = new SendMessage();
        try {
            mimeMessageHelper = new MimeMessageHelper(mimeMessage, true, ENCODING);
        } catch (MessagingException e) {
            logger.info("time: {} MailMessageFactory init occured an exception {}", new Date(), e);
        }
    }

    /**
     * 设置收件人地址
     */
    public MailMessageFactory setTo(List<String> tos) {
        sendMessage.setTos(tos);
        return this;
    }

    /**
     * 设置邮件主题
     */
    public MailMessageFactory setSubject(String subject) {
        sendMessage.setSubject(subject);
        return this;
    }

    /**
     * 设置邮件内容
     */
    public MailMessageFactory setText(String text) {
        sendMessage.addText(text);
        return this;
    }

    /**
     * 设置邮件的图片
     *
     * @param file
     */
    public MailMessageFactory setImgFile(String imageName, File file) {
        try {
            sendMessage.addFile(MimeUtility.encodeWord(imageName), file);
        } catch (UnsupportedEncodingException e) {
            logger.info("time: {} MailMessageFactory setImgFile occured an exception {}", new Date(), e);
        }
        return this;
    }

    /**
     * 设置邮件的图片
     *
     * @param filePath
     */
    public MailMessageFactory setImgFile(String imageName, String filePath) {
        setImgFile(imageName, new File(filePath));
        return this;
    }

    /**
     * 发送邮件
     */
    public void send() {
        sendMessage.setForm(EmailEntity.EMAIL_FROM);
        List<String> tos = sendMessage.getTos();
        sendMessage.setTos(tos);
        // 实际的邮件发送者 sendHtmlImgFileMessage
        sendHtmlImgFileMessage();
    }

    /**
     * 发送图片html邮件
     */
    private void sendHtmlImgFileMessage() {
        try {
            mimeMessageHelper.setFrom(sendMessage.getForm());
            mimeMessageHelper.setSubject(sendMessage.getSubject());
            mimeMessageHelper.setText(sendMessage.getSendTexts(), true);
            int imgSize = sendMessage.getImages().size();
            if (imgSize > 0) {
                List<SendMessage> lists = sendMessage.getImages();
                FileSystemResource fsr = null;
                String imgName = null;
                for (SendMessage entity : lists) {
                    fsr = new FileSystemResource(entity.getFile());
                    imgName = entity.getImgName();
                    mimeMessageHelper.addInline(imgName, fsr);
                }
                fsr = null;
            }
        } catch (MessagingException e) {
            logger.info("time:{},send email occured an exception {}", new Date(), e);
        }
        // 获取收件人列表，给每个人发送邮件
        List<String> tos = sendMessage.getTos();
        for (String to : tos) {
            try {
                mimeMessageHelper.setTo(to);
                senderImpl.send(mimeMessage);
            } catch (MessagingException e) {
                logger.info("time:{},send email occured an exception {}", new Date(), e);
            }

        }

    }
}
